#### Script to do multiple treeMI imputations for the carbon black industry
### and export the imputed dataset

#### input files:
####	carbonf_gooddata.csv
####
#### output files:
####    carbon_imputes.csv
####    carbon_predicted.csv

require(tree)


#### read in the "good" dataset, in which we have replaced the Census Bureau imputes/edits with missing values
carbon_gooddata<-read.csv("carbonf_gooddata.csv",header=TRUE)

### Create completed datasets using treeMI:

carbon_imputes<-treeMI(carbon_gooddata,ITER=10,c(1,0,0,0,0,0,0,0,1,0,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 5, startDev = 0.000001) 


carbon_imputes$impSet$impsetnum <- 1
carbon_imputes$PPDsample$impsetnum <- 1

### For the first imputed dataset, create a new file
write.table(carbon_imputes$impSet,file="carbon_imputes.csv",append=FALSE,sep=",") 
write.table(carbon_imputes$PPDsample,file="carbon_predicted.csv",append=FALSE,sep=",") 

for (j in 2:500) {

  carbon_imputes<-treeMI(carbon_gooddata,ITER=10,c(1,0,0,0,0,0,0,0,1,0,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 5, startDev = 0.000001) 
  carbon_imputes$impSet$impsetnum <- j
  carbon_imputes$PPDsample$impsetnum <- j

  ### Append the subsequent imputed datasets to the file created for the first dataset

  write.table(carbon_imputes$impSet,file="carbon_imputes.csv",append=TRUE,sep=",",col.names=FALSE) 
  write.table(carbon_imputes$PPDsample,file="carbon_predicted.csv",append=TRUE,sep=",",col.names=FALSE) 

}


